package login

import (
	"github.com/gin-gonic/gin"
	"github.com/vueadmin/app/admin/common/captcha"
	"github.com/vueadmin/app/admin/internal/dto"
	"github.com/vueadmin/app/admin/internal/logic"
	"github.com/vueadmin/app/admin/internal/svc"
	"github.com/vueadmin/utils"
	"github.com/vueadmin/utils/common/result"
	"github.com/vueadmin/utils/conv"
	"github.com/vueadmin/utils/response"
	"io/ioutil"
	"net/http"
	"strings"
)

// 用户登录
func Login(c *gin.Context, svcCtx *svc.ServiceContext) {
	req := dto.LoginReq{}
	if err := utils.BindAndValid(c, &req); err != nil {
		response.Fail(c, err.Error())
		return
	}
	l := logic.NewLoginLogic(c, svcCtx)
	token, err := l.Login(&req)
	if err != nil {
		response.Err(c, err)
		return
	}
	go func() {
		l.CreateLoginLog(&req)
	}()
	response.Success(c, "success", token)
}

// 验证码
func Captcha(c *gin.Context, svcCtx *svc.ServiceContext) {
	response.Success(c, "success", result.M{
		"captcha":     captcha.Generate(svcCtx),
		"site_title":  c.Value("site_title"),
		"success_url": "/admin/Home/index",
	})
}

// 阿里云oss客户端上传回调
func AliOssCallBack(c *gin.Context, svcCtx *svc.ServiceContext) {
	bodyData, _ := ioutil.ReadAll(c.Request.Body)
	body := string(bodyData)
	if conv.IsEmpty(body) {
		response.Fail(c, "回调数据不能为空")
		return
	}
	url := utils.GetEndPoint(svcCtx.Config.Upload.AliyunOss.Callback+strings.ReplaceAll(body, "%2F", "/"), svcCtx.Config.Upload.AliyunOss.BucketName)
	c.JSON(http.StatusOK, map[string]interface{}{
		"code": 1,
		"data": strings.TrimRight(url, "="),
	})
}

// 退出登录
func Logout(c *gin.Context, svcCtx *svc.ServiceContext) {
	response.Success(c, "退出登录", nil)
}
